<template>
	<div class="toolbar">
		<el-button type="primary" icon="Plus" @click="router.push('/recruit/consult/add')">新建咨询</el-button>
		<el-button type="primary" icon="Plus">办理入学</el-button>
	</div>
	<el-row style="margin-top:10px;" :gutter="20">
		<el-col :span="16">
			<el-card header="我的任务" shadow="never">
				<div class="date_picker">
					<el-date-picker v-model="currentDate.date" placeholder="自定义时间"></el-date-picker>
					<span style="font-size: 18px;color: gray;">{{ currentDate.dateStr }}</span>
					<el-link type="primary" :underline="false" @click="toNow">回到今天</el-link>
				</div>
				<!-- 时间列表 -->
				<div class="date_list">
					<div class="date_card" @click="changeWeek(0)">
						<el-icon>
							<ArrowLeft />
						</el-icon>
					</div>
					<div v-for="(item, index) in weekDays" :key="index" class="date_card"
						:class="{ 'active_card': currentDate.dateStr === item.dateStr }"
						@click="currentDate.date = item.date">
						<span>{{ item.week }}</span>&nbsp;
						<span>{{ item.date.getMonth() + 1 }}.{{ item.date.getDate() }}</span>
					</div>
					<div class="date_card" @click="changeWeek(1)">
						<el-icon>
							<ArrowRight />
						</el-icon>
					</div>
				</div>
				<!-- 任务 -->
				<div v-if="clientList.length">
					<el-table :data="clientList" border style="margin-top: 10px;">
						<el-table-column type="index" label="序号" align="center" width="55"></el-table-column>
						<el-table-column label="姓名" prop="name" align="center"></el-table-column>
						<el-table-column label="手机号" prop="mobile" align="center"></el-table-column>
						<el-table-column label="微信" prop="wechat" align="center"></el-table-column>
						<el-table-column label="意向度" align="center" width="150">
							<template #="{ row }">
								<el-rate v-model="row.purpose" disabled></el-rate>
							</template>
						</el-table-column>
						<el-table-column label="操作" align="center" width="100">

							<template #="{ row }">
								<el-link type="primary" icon="List" :underline="false">查看详情</el-link>
								<el-link type="success" icon="Avatar" :underline="false">办理报名</el-link>
								<el-link type="danger" icon="Edit" :underline="false">跟进信息</el-link>
								<el-link type="warning" icon="Edit" :underline="false">编辑信息</el-link>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div v-else class="no_client">
					<el-icon size="100" color="#F2F5F7">
						<FolderDelete />
					</el-icon>
					<div>没有任务</div>
				</div>
			</el-card>
		</el-col>
		<el-col :span="8">
			<el-card header="我的成交额" shadow="never">
				<el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
					end-placeholder="截止时间" style="width: 92%;" @change="onDatePickerChange" format="YYYY-MM-DD"
					value-format="YYYY-MM-DD hh:mm:ss" />
				<div class="aside_icon">
					<div class="aside_icon_item">
						<div class="aside_icon_item_icon">
							<el-icon size="30" color="#24BCFF">
								<Monitor />
							</el-icon>
						</div>
						<div class="aside_icon_item_content">
							<div class="aside_icon_item_text">
								成交人数(人)
							</div>
							<div class="aside_icon_item_number">
								{{ transaction.peopleNum }}
							</div>
						</div>
					</div>
					<div class="aside_icon_item">
						<div class="aside_icon_item_icon">
							<el-icon size="30" color="#DEA361">
								<Money />
							</el-icon>
						</div>
						<div class="aside_icon_item_content">
							<div class="aside_icon_item_text">
								应收成交额(元)
							</div>
							<div class="aside_icon_item_number">
								{{ transaction.receivableAmount || '暂无' }}
							</div>
						</div>
					</div>
					<div class="aside_icon_item">
						<div class="aside_icon_item_icon">
							<el-icon size="30" color="#5F88CD">
								<EditPen />
							</el-icon>
						</div>
						<div class="aside_icon_item_content">
							<div class="aside_icon_item_text">
								成交订单(笔)
							</div>
							<div class="aside_icon_item_number">
								{{ transaction.orderNum }}
							</div>
						</div>
					</div>
					<div class="aside_icon_item">
						<div class="aside_icon_item_icon">
							<el-icon size="30" color="#C85390">
								<Calendar />
							</el-icon>
						</div>
						<div class="aside_icon_item_content">
							<div class="aside_icon_item_text">
								订单实收(元)
							</div>
							<div class="aside_icon_item_number">
								{{ transaction.actualAmount || '暂无' }}
							</div>
						</div>
					</div>
				</div>
			</el-card>
			<!-- 漏斗图 -->
			<el-card header="我的漏斗" shadow="never" style="margin-top: 10px;">
				<el-date-picker v-model="timeRangeFunnel" type="datetimerange" range-separator="至"
					start-placeholder="开始时间" end-placeholder="截止时间" style="width: 92%;"
					@change="onDatePickerChangeFunnel" format="YYYY-MM-DD" value-format="YYYY-MM-DD hh:mm:ss" />
				<!-- 图表 -->
				<div ref="funnelDom" style="height: 250px;"></div>
				<div class="funnel_rate">
					<div>
						<h3>
							成功率:
							<el-text type="primary">{{ successRate }}%</el-text>
						</h3>
						<span>(已成交/全部咨询)</span>
					</div>
					<div>
						<h3>
							失败率:
							<el-text type="primary">{{ failRate }}%</el-text>
						</h3>
						<span>(已退款/全部咨询)</span>
					</div>
				</div>
			</el-card>
		</el-col>
	</el-row>
</template>

<script setup lang="ts">
import { getConsultPageApi, getStatisticFunnelApi, getStatisticTransactionApi } from '@renderer/api/recruit';
import { Funnel, RecruitItem, SearchRecruit, Transaction } from '@renderer/interface/recruit';
import router from '@renderer/router';
import { tool } from '@renderer/utils/tool';
import { computed, onMounted, reactive, watch } from 'vue';
import { ref } from 'vue';
import * as echarts from 'echarts'
import { EChartsOption } from 'echarts';

/* 日期选择：我的任务 */
// 将 Date 形式的日期转换为 YYYY-MM-DD 形式并返回
const toggleDate = (date: Date) => {
	return date ? tool.dateFormat(date).split(' ')[0] : '请选择日期'
}
interface IDate {
	date: Date
	dateStr: string
	week: string
}
const currentDate = ref<IDate>({
	date: new Date(),
	dateStr: toggleDate(new Date()),
	week: ''
})
const toNow = () => {
	currentDate.value.date = new Date()
}
// 星期数据
const weekDays = ref<IDate[]>([
	{ week: '周日', date: new Date(), dateStr: '' },
	{ week: '周一', date: new Date(), dateStr: '' },
	{ week: '周二', date: new Date(), dateStr: '' },
	{ week: '周三', date: new Date(), dateStr: '' },
	{ week: '周四', date: new Date(), dateStr: '' },
	{ week: '周五', date: new Date(), dateStr: '' },
	{ week: '周六', date: new Date(), dateStr: '' },
])
const changeDate = () => {
	weekDays.value.forEach((item, index) => {
		// 计算出每个日期与当前日期的差值
		const diffDay = currentDate.value.date.getDay() - index

		// 预设一个目标日期
		const targetDate = new Date()
		targetDate.setFullYear(currentDate.value.date.getFullYear())
		targetDate.setMonth(currentDate.value.date.getMonth())
		targetDate.setDate(currentDate.value.date.getDate() - diffDay)

		item.date = targetDate
		item.dateStr = toggleDate(targetDate)
	})
}
// 切换星期
const changeWeek = (flag: number) => {
	weekDays.value.forEach(item => {
		item.date.setDate(item.date.getDate() + (flag ? 7 : -7))
		item.dateStr = toggleDate(item.date)
	})
}

/* 任务列表 */
// 搜索任务表单
const clientForm = reactive<SearchRecruit>({
	size: 100,
	page: 1,
	startTime: '',
	endTime: ''
})
// 任务列表
const clientList = ref<RecruitItem[]>([])
// 获取任务列表
const getConsultPageData = async () => {
	clientForm.startTime = currentDate.value.dateStr + ' 00:00:00'
	clientForm.endTime = currentDate.value.dateStr + ' 23:59:59'
	const { code, data } = await getConsultPageApi(clientForm)
	if (code !== '200') return

	clientList.value = data.records
}

/* 我的成交额 */
// 预设日期
const toDayStr = tool.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
const tomorrow = new Date()
tomorrow.setDate(new Date().getDate() + 1)
const tomorrowStr = tool.dateFormat(tomorrow, 'yyyy-MM-dd hh:mm:ss')
const timeRange = ref<any>([toDayStr, tomorrowStr])
// 成交额
const transaction = ref<Transaction>({
	peopleNum: 0,
	orderNum: 0,
	receivableAmount: 0,
	actualAmount: 0
})
// 获取成交额数据
const getStatisticTransactionData = async () => {
	const { code, data } = await getStatisticTransactionApi({ startDate: timeRange.value[0], endDate: timeRange.value[1] })
	if (code !== '200') return

	transaction.value = data
}
const onDatePickerChange = () => {
	getStatisticTransactionData()
}

/* 漏斗图 */
const timeRangeFunnel = ref<any>([toDayStr, tomorrowStr])
// 漏斗图实例
const funnelDom = ref<HTMLDivElement>()
const funnel = ref<Funnel[]>([])
const successRate = computed(() => {
	if (funnel.value.length) {
		const success = funnel.value.find(item => item.name === '已成交')!.value
		const total = funnel.value.find(item => item.name === '全部咨询')!.value
		if (total) {
			return success / total * 100
		} else return 0
	} else return 0
})
const failRate = computed(() => {
	if (funnel.value.length) {
		const fail = funnel.value.find(item => item.name === '已退款')!.value
		const total = funnel.value.find(item => item.name === '全部咨询')!.value
		if (total) {
			return fail / total * 100
		} else return 0
	} else return 0
})
// 获取漏斗图数据
const getStatisticFunnelData = async () => {
	const { code, data } = await getStatisticFunnelApi({ startDate: timeRangeFunnel.value[0], endDate: timeRangeFunnel.value[1] })
	if (code !== '200') return

	funnel.value = data
	const myChart = echarts.init(funnelDom.value)
	const option: EChartsOption = {
		tooltip: {
			trigger: 'item',
		},
		series: [
			{
				type: 'funnel',
				data: data.map(item => ({ name: item.name, value: item.value }))
			}
		]
	}
	myChart.setOption(option)
}
const onDatePickerChangeFunnel = () => {
	getStatisticFunnelData()
}

/* 组件api */
watch(() => currentDate.value.date, (val) => {
	currentDate.value.dateStr = toggleDate(val)
	if (val) {
		// 获取星期的数据
		changeDate()
		// 获取客户列表
		getConsultPageData()
	}
}, { immediate: true })
onMounted(() => {
	getStatisticTransactionData()
	getStatisticFunnelData()
})
</script>

<style scoped lang="scss">
.date_picker {
	margin-bottom: 10px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.date_list {
	display: flex;

	.date_card {
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		border-radius: 4px;
		background-color: #F2F5F7;
		margin: 0 2px;
		width: 90px;
		height: 40px;
		font-size: 10px;
	}

	.active_card {
		color: white;
		background-color: #409EFF;
	}
}

.no_client {
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	height: 300px;
	font-style: italic;
	color: #F2F5F7;
	font-weight: normal;
}

.aside_icon {
	display: flex;
	flex-wrap: wrap;

	.aside_icon_item {
		display: flex;
		align-items: center;
		width: 50%;
		margin-top: 10px;

		.aside_icon_item_content {
			height: 100%;
			margin-left: 5px;
			font-size: 10px;
			font-weight: 15px;
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;

			.aside_icon_item_number {
				font-size: 15px;
			}
		}
	}
}

.funnel_rate {
	display: flex;
	justify-content: space-between;

	span {
		font-size: 12px;
	}
}
</style>